package org.sfilo.downloader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class SiteFileFetch implements Observer
{
	SiteInfoBean site;
	List<FrameFileSpider> spiders = new ArrayList<FrameFileSpider>();
	int numberOfSpiders = 10;

	public SiteFileFetch(SiteInfoBean site, int numberOfSpiders)
	{
		this.site = site;
		this.numberOfSpiders = numberOfSpiders;
	}

	private boolean completeFlag = false;

	public boolean isComplete()
	{
		return completeFlag;
	}

	public void work() throws Exception
	{
		produceSpider();

		executeSpider();

	}

	private void executeSpider()
	{
		Iterator<FrameFileSpider> itor = spiders.iterator();

		while (itor.hasNext())
		{
			final FrameFileSpider spider = itor.next();
			new Thread(new Runnable()
			{

				@Override
				public void run()
				{
					try
					{
						spider.scratch();
					}
					catch (Exception ex)
					{
						ex.printStackTrace();
					}
				}

			}).start();
		}
	}

	private void produceSpider() throws Exception
	{
		int length = SiteInfoUtil.getLength(site);
		int sublength = length / numberOfSpiders;
		int lastLength = length % numberOfSpiders;
		
		for (int i = 0; i < numberOfSpiders; i++)
		{
			FrameFileSpider spider = SpiderFactory.createSpider(site, i * sublength, sublength, site
					.getDestFileName());
			if (spider instanceof Observable)
			{
				((Observable) spider).addObserver(this);
			}
			spiders.add(spider);

		}
		if (lastLength != 0)
		{
			FrameFileSpider spider = SpiderFactory.createSpider(site, numberOfSpiders * sublength,
					lastLength, site.getDestFileName());
			if (spider instanceof Observable)
			{
				((Observable) spider).addObserver(this);
			}
			spiders.add(spider);
		}

	}

	@Override
	public void update(Observable arg0, Object event)
	{
		SpiderEvent spiderEvent = (SpiderEvent) event;
		if (spiderEvent == SpiderEvent.DOWNLOADCOMPLETE)
		{
			spiders.remove(arg0);
			if (spiders.size() == 0)
			{
				completeFlag = true;
			}

		}

	}

}
